<script setup lang="ts">
import { LOGIN_DEVICE_ENUM } from '@/enums/loginDeviceEnum';
import { encryptData } from '@/lib/encrypt';
import { getCaptcha } from '@/services/api/auth';
import { useUserStore } from '@/stores/modules/user';
import { Toast } from '@/utils/uniapi/prompt';
import { onLoad } from '@dcloudio/uni-app';
import { omit } from 'lodash-es';
import { useRouter } from 'uni-mini-router';
import { computed, reactive, ref, unref } from 'vue';

const pageQuery = ref<Record<string, any> | undefined>(undefined);
onLoad((query) => {
  pageQuery.value = query;
  fetchCaptcha();
});

const router = useRouter();

const captcha = reactive({
  key: '',
  base64: '',
  code: '',
});
const captchaError = ref('');

const loginMode = ref<'username' | 'email'>('username'); // 登录方式切换

const form = reactive({
  username: 'admin',
  email: 'admin@example.com',
  password: '123456',
});

const passwordVisible = ref(false);
const isLoading = ref(false);
const usernameError = ref('');
const emailError = ref('');
const passwordError = ref('');

const userStore = useUserStore();

// 验证邮箱格式
function validateEmail(email: string) {
  const re = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/;
  return re.test(email);
}

// 验证用户名格式
function validateUsername(username: string) {
  return username.length >= 3 && username.length <= 20;
}

const loginTitle = computed(() => {
  return loginMode.value === 'username' ? '用户名登录' : '邮箱登录';
});

const placeholderText = computed(() => {
  return loginMode.value === 'username' ? '请输入用户名' : '请输入邮箱';
});

// 获取验证码
async function fetchCaptcha() {
  try {
    const res = await getCaptcha();
    captcha.key = res.captchaKey;
    captcha.base64 = res.captchaBase64Image;
  } catch (error) {
    console.error('获取验证码失败:', error);
    Toast('获取验证码失败，请重试');
  }
}

// 点击验证码刷新
async function refreshCaptcha() {
  await fetchCaptcha();
  captcha.code = '';
  captchaError.value = '';
}

// 跳转到注册页面
function goToRegister() {
  router.push({ name: 'Register' });
}

async function submit() {
  if (isLoading.value)
    return;

  // 表单验证
  usernameError.value = '';
  emailError.value = '';
  passwordError.value = '';
  captchaError.value = '';

  if (loginMode.value === 'username') {
    if (!form.username) {
      usernameError.value = '请输入用户名';
      return;
    }

    if (!validateUsername(form.username)) {
      usernameError.value = '用户名需3-20位字符';
      return;
    }
  } else {
    if (!form.email) {
      emailError.value = '请输入邮箱';
      return;
    }

    if (!validateEmail(form.email)) {
      emailError.value = '邮箱格式不正确';
      return;
    }
  }

  if (!form.password) {
    passwordError.value = '请输入密码';
    return;
  }

  if (!captcha.code) {
    captchaError.value = '请输入验证码';
    return;
  }

  try {
    isLoading.value = true;
    const loginData = {
      ...(loginMode.value === 'username'
        ? { username: form.username }
        : { email: form.email }),
      password: encryptData(form.password),
      captchaKey: captcha.key,
      captchaCode: captcha.code,
      loginDevice: LOGIN_DEVICE_ENUM.H5.value.toString(),
    };

    await userStore.login(loginData);

    Toast('登录成功', { duration: 1500 });
    setTimeout(() => {
      if (unref(pageQuery)?.redirect) {
        const params = omit(unref(pageQuery), ['redirect', 'tabBar']);
        if (unref(pageQuery)) {
          unref(pageQuery)?.tabBar === 'true'
            ? router.replaceAll({ name: unref(pageQuery)?.redirect, params })
            : router.replace({ name: unref(pageQuery)?.redirect, params });
        }
      } else {
        console.log('no redirect', router);
        router.back();
      }
    }, 1500);
  } catch (error) {
    // 登录失败时刷新验证码
    refreshCaptcha();
    Toast('登录失败，请检查账号密码');
  } finally {
    isLoading.value = false;
  }
}

function switchLoginMode() {
  loginMode.value = loginMode.value === 'username' ? 'email' : 'username';
}
</script>

<template>
  <view class="min-h-screen bg-gradient-to-b from-blue-50 to-white">
    <!-- 顶部背景 -->
    <view class="h-40 bg-gradient-to-br from-blue-600 to-blue-400 relative overflow-hidden flex items-end">
      <view class="absolute inset-0 opacity-10">
        <view class="absolute top-10 left-10 w-32 h-32 rounded-full bg-white" />
        <view class="absolute bottom-20 right-20 w-40 h-40 rounded-full bg-white" />
      </view>
      <view class="absolute bottom-8 left-8 animate-fade-in">
        <text class="text-3xl font-bold text-white">
          欢迎回来
        </text>
        <text class="block text-white/90 mt-2 text-base">
          选择您喜欢的登录方式
        </text>
      </view>
    </view>

    <!-- 登录表单 -->
    <view class="mx-5 -mt-6 bg-white rounded-2xl shadow-xl p-6 relative z-10 animate-fade-in">
      <view class="text-2xl font-bold text-gray-800 mb-6 flex items-center justify-between">
        <view class="flex items-center">
          <view class="w-2 h-6 bg-gradient-to-b from-blue-500 to-blue-300 rounded-full mr-3" />
          {{ loginTitle }}
        </view>
        <text
          class="text-sm text-blue-500 active:opacity-70 transition-colors"
          @click="switchLoginMode"
        >
          {{ loginMode === 'username' ? '使用邮箱登录' : '使用用户名登录' }}
        </text>
      </view>

      <!-- 用户名/邮箱输入部分 -->
      <view class="mb-5">
        <view class="text-sm text-gray-600 mb-2 font-medium flex justify-between">
          <text>{{ loginMode === 'username' ? '用户名' : '邮箱' }}</text>
          <text v-if="loginMode === 'username' ? usernameError : emailError" class="text-red-500 text-xs">
            {{ loginMode === 'username' ? usernameError : emailError }}
          </text>
        </view>
        <view class="relative">
          <!-- 用户名 -->
          <input
            v-if="loginMode === 'username'"
            v-model="form.username"
            class="w-full px-4 h-12 border border-gray-200 rounded-lg focus:outline-none focus:border-blue-500 transition-all text-gray-800 placeholder-gray-400 bg-gray-50"
            :placeholder="placeholderText"
            type="text"
            :disabled="isLoading"
            confirm-type="next"
            @focus="loginMode === 'username' ? usernameError = '' : emailError = ''"
          >
          <!-- 邮箱 -->
          <input
            v-else
            v-model="form.email"
            class="w-full px-4 h-12 border border-gray-200 rounded-lg focus:outline-none focus:border-blue-500 transition-all text-gray-800 placeholder-gray-400 bg-gray-50"
            :placeholder="placeholderText"
            type="text"
            :disabled="isLoading"
            confirm-type="next"
            @focus="loginMode === 'email' ? usernameError = '' : emailError = ''"
          >
          <view class="absolute right-3 top-3 text-blue-500">
            <i-mdi-account-outline v-if="loginMode === 'username'" class="w-5 h-5" />
            <i-mdi-email-outline v-else class="w-5 h-5" />
          </view>
        </view>
      </view>

      <!-- 密码输入部分 -->
      <view class="mb-6">
        <view class="text-sm text-gray-600 mb-2 font-medium flex justify-between">
          <text>密码</text>
          <text v-if="passwordError" class="text-red-500 text-xs">
            {{ passwordError }}
          </text>
        </view>
        <view class="relative">
          <input
            v-model="form.password"
            :type="passwordVisible ? 'text' : 'password'"
            class="w-full px-4 h-12 border border-gray-200 rounded-lg focus:outline-none focus:border-blue-500 transition-all text-gray-800 placeholder-gray-400 pr-12 bg-gray-50"
            placeholder="请输入密码"
            :disabled="isLoading"
            confirm-type="next"
            @input="form.password = $event.detail.value"
            @focus="passwordError = ''"
          >
          <view class="absolute right-3 top-3 flex space-x-2">
            <view
              class="text-gray-400 active:opacity-70"
              @click.stop="passwordVisible = !passwordVisible"
            >
              <i-mdi-eye-off-outline v-if="!passwordVisible" class="w-5 h-5" />
              <i-mdi-eye-outline v-else class="w-5 h-5" />
            </view>
          </view>
        </view>
      </view>

      <!-- 验证码部分 -->
      <view class="mb-6">
        <view class="text-sm text-gray-600 mb-2 font-medium flex justify-between">
          <text>验证码</text>
          <text v-if="captchaError" class="text-red-500 text-xs">
            {{ captchaError }}
          </text>
        </view>
        <view class="flex items-center gap-3">
          <input
            v-model="captcha.code"
            class="flex-1 px-4 h-12 border border-gray-200 rounded-lg focus:outline-none focus:border-blue-500 transition-all text-gray-800 placeholder-gray-400 bg-gray-50"
            placeholder="请输入验证码"
            type="text"
            :disabled="isLoading"
            confirm-type="done"
            @focus="captchaError = ''"
            @input="captcha.code = $event.detail.value"
            @confirm="submit"
          >
          <view
            class="w-36 h-12 bg-gray-100 rounded-lg flex items-center justify-center cursor-pointer overflow-hidden"
            @click="refreshCaptcha"
          >
            <image
              v-if="captcha.base64"
              :src="captcha.base64"
              mode="aspectFill"
              class="w-full h-full"
            />
            <i-mdi-refresh v-else class="w-6 h-6 text-gray-400" />
          </view>
        </view>
      </view>

      <!-- 忘记密码 -->
      <view class="text-right mb-6">
        <text
          class="text-sm text-blue-500 active:opacity-70 transition-colors"
          @click="router.push({ name: 'ForgetPassword' })"
        >
          忘记密码？
        </text>
      </view>

      <!-- 登录按钮 -->
      <button
        class="w-full py-3 bg-gradient-to-r from-blue-500 to-blue-400 text-white rounded-xl shadow-lg active:opacity-90 transition-all flex items-center justify-center h-12"
        :class="{ 'opacity-80': isLoading }"
        :disabled="isLoading"
        hover-class="scale-95"
        hover-stay-time="100"
        @click="submit"
      >
        <i-mdi-loading v-if="isLoading" class="animate-spin w-5 h-5 mr-2" />
        <text class="font-medium">
          {{ isLoading ? '登录中...' : '登 录' }}
        </text>
      </button>

      <!-- 注册提示 -->
      <view class="mt-6 text-center text-sm text-gray-600">
        还没有账号？
        <text
          class="text-blue-500 font-medium active:opacity-70 transition-colors"
          @click="goToRegister"
        >
          立即注册
        </text>
      </view>
    </view>

    <!-- 第三方登录 -->
    <view class="mx-5 mt-8 animate-fade-in">
      <view class="relative flex items-center justify-center mb-6">
        <view class="h-px bg-gray-200 flex-1" />
        <text class="px-3 text-sm text-gray-500 bg-gray-50">
          其他登录方式
        </text>
        <view class="h-px bg-gray-200 flex-1" />
      </view>

      <view class="flex justify-center space-x-8">
        <view
          class="w-12 h-12 bg-gray-50 rounded-full flex items-center justify-center shadow-sm active:bg-gray-100 transition-all active:scale-90"
          hover-class="scale-105"
          hover-stay-time="100"
          @click="Toast('微信登录即将开放')"
        >
          <i-mdi-wechat class="w-7 h-7 text-[#09bb07]" />
        </view>
        <view
          class="w-12 h-12 bg-gray-50 rounded-full flex items-center justify-center shadow-sm active:bg-gray-100 transition-all active:scale-90"
          hover-class="scale-105"
          hover-stay-time="100"
          @click="Toast('QQ登录即将开放')"
        >
          <i-mdi-qqchat class="w-7 h-7 text-[#12b7f5]" />
        </view>
        <view
          class="w-12 h-12 bg-gray-50 rounded-full flex items-center justify-center shadow-sm active:bg-gray-100 transition-all active:scale-90"
          hover-class="scale-105"
          hover-stay-time="100"
          @click="Toast('邮箱验证码登录即将开放')"
        >
          <i-mdi-email-fast-outline class="w-7 h-7 text-[#e6162d]" />
        </view>
      </view>
    </view>

    <!-- 底部版权信息 -->
    <view class="text-center text-xs text-gray-400 mt-10 pb-5">
      ©2025 博客管理平台
    </view>
  </view>
</template>

<style lang="scss">
/* 自定义动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in {
  animation: fadeIn 0.5s ease-out;
}

/* 按钮缩放效果 */
.scale-95 {
  transform: scale(0.95);
}

.scale-105 {
  transform: scale(1.05);
}

/* 过渡效果 */
.transition-all {
  transition: all 0.3s ease;
}

/* 输入框样式增强 */
.input-focus {
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}
</style>
